package com.mwl.gateway.utils;

import com.mwl.gateway.constant.GlobalVariable;
import jakarta.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * description:
 *
 * @author maweilong
 **/
public class MdcUtils {
    private static final Logger log = LoggerFactory.getLogger(MdcUtils.class);
    /**
     * 从ReactorContext中获取需要传递的信息
     */
    public static Mono<Map<String, String>> getMDCContext() {
        return Mono.deferContextual(view -> {
            if (view.isEmpty() || !view.hasKey(GlobalVariable.MDC_KEY)) {
                return Mono.just(Map.of());
            }
            Object o = view.get(GlobalVariable.MDC_KEY);
            Map<String, String> ctx = (Map<String, String>) o;
            return Mono.just(ctx);
        });
    }
    /**
     * 验证MDC中的traceId与是否与预期值一致
     *
     * @param target 预期的traceId值
     * @param mark   标记调试位置
     */
    public static String checkMDC(@Nonnull String target, @Nonnull String mark) {
        String traceIe = MDC.get(GlobalVariable.MDC_KEY);
        if (!target.equals(traceIe)) {
            log.error("{} MDC value not matching {} -> {}", mark, target, traceIe);
        }
        return traceIe;
    }
}
